﻿using System;
using ITViet.Domains;
using ITViet.Services;
using ITViet.Web.App_Code;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxCallback;
using Library.Encryption;

namespace ITViet.Web.Admin
{
  public partial class UserList : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.UserList;
      }
    }
    #endregion

    #region Methods

    internal override void SetPermission()
    {
      if (!CanModify) btnAdd.Visible = btnSave.Visible = false;
    }

    private void LoadPage()
    {
      hfCurrentUser.Value = CurrentUser.Username;
      hfDefaultPassword.Value = GlobalCache.Instance.DefaultUserPassword;
    }

    private void LoadUserList()
    {
      gvUser.DataSource = new UserService().GetAll();
      gvUser.DataBind();
    }

    private string SaveUser()
    {
      try
      {
        UserService usrService = new UserService();
        Domains.User user = null;
        string status = (cbxStatus.Value != null) ? cbxStatus.Value.ToString() : CommonStatus.Active;

        string userName = hfUserId.Value.ToString();

        if (!string.IsNullOrEmpty(userName))
        {
          user = usrService.GetByUsername(userName);
          if (user == null)
            return "Save|" + Resources.Messages.ERR0003;
        }
        else
        {
          user = usrService.GetByUsername(txtUsername.Text);
          if (user != null)
            return "Save|" + Resources.Messages.ERR0012;
          user = new Domains.User();
          user.CreatedBy = CurrentUser.Username;
          user.CreatedDate = DateTime.Now;
          user.Username = txtUsername.Text;
          user.Password = Library.Encryption.MD5.Encrypt(txtDefaultPassword.Text);
        }

        user.Fullname = txtFullName.Text;
        user.Email = txtEmail.Text;
        user.Status = status;
        usrService.Save(user);
      }
      catch (Exception ex)
      {
        WriteLog("UserList.aspx :: Save User", ex);
        return "Save|" + Resources.Messages.ERR0004;
      }
      return "Save|";
    }

    private string DeleteUser(string userName)
    {
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          UserGroupService ugService = new UserGroupService();
          TList<UserGroup> ugList = ugService.GetByUsername(userName);
          ugService.Delete(ugList);
          new UserService().Delete(userName);
          ConnectionScope.Complete();
        }
      }
      catch (Exception ex)
      {
        WriteLog("UserList.aspx :: Delete User", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string ResetPassword()
    {
      try
      {
        long userId = 0;
        string userName = hfUserId.Value;
        long.TryParse(hfUserId.Value, out userId);
        UserService uService = new UserService();
        Domains.User user = uService.GetByUsername(userName);
        if (user != null)
        {
          user.Password = MD5.Encrypt(GlobalCache.Instance.DefaultUserPassword);
          uService.Save(user);
        }
        else
          return Resources.Messages.ERR0003;
      }
      catch (Exception ex)
      {
        WriteLog("UserList.aspx :: Reset Password", ex);
        return Resources.Messages.ERR0004;
      }
      return String.Format(Resources.Messages.ERR0010, GlobalCache.Instance.DefaultUserPassword);
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      xdsStatus.DataFile = XmlStatusFile;
      if (!IsCallback && !IsPostBack)
      {
        LoadPage();
        LoadUserList();
      }
      if (gvUser.IsCallback)
        LoadUserList();
    }

    protected void ctrlCallback_Callback(object source, CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "ResetPassword")
      {
        e.Result = ResetPassword();
      }
    }

    protected void gvUser_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Save")
      {
        m_innerError = SaveUser();
        LoadUserList();
      }
      else if (para[0] == "Delete")
      {
        m_innerError = DeleteUser(para[1]);
        LoadUserList();
      }
    }

    protected void gvUser_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvUser_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
    {
      GridViewCommandColumnButton deleteButton = e.Column.DeleteButton;
      if (deleteButton != null && !CanDelete) deleteButton.Visible = false;

      if (!CanModify && e.Button.ButtonType == DevExpress.Web.ASPxGridView.ColumnCommandButtonType.Edit)
      {
        e.Visible = false;
      }
    }

    #endregion
  }
}
